package com.iflytek.aidemo;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.iflytek.aidemo.api.ApiService;
import com.iflytek.aidemo.api.ApiServiceImpl;
import com.iflytek.aidemo.model.ApiResponse;
import com.iflytek.aidemo.model.User;
import com.iflytek.aidemo.util.SessionManager;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class LoginActivity extends AppCompatActivity {

    private EditText etUsername, etPassword;
    private Button btnLogin;
    private TextView tvRegister;
    private ProgressBar progressBar;
    private ImageView ivPasswordToggle;
    
    private ApiService apiService;
    private SessionManager sessionManager;
    private ExecutorService executorService;
    private Handler mainHandler;
    private boolean isPasswordVisible = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initViews();
        initData();
        setupListeners();
        
        // 检查是否已登录
        checkLoginStatus();
    }

    private void initViews() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        btnLogin = findViewById(R.id.btn_login);
        tvRegister = findViewById(R.id.tv_register);
        progressBar = findViewById(R.id.progress_bar);
        ivPasswordToggle = findViewById(R.id.iv_password_toggle);
    }

    private void initData() {
        apiService = new ApiServiceImpl();
        sessionManager = new SessionManager(this);
        executorService = Executors.newSingleThreadExecutor();
        mainHandler = new Handler(Looper.getMainLooper());
    }

    private void setupListeners() {
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                performLogin();
            }
        });

        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到注册页面
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });

        // 添加密码显示/隐藏的点击事件
        ivPasswordToggle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                togglePasswordVisibility();
            }
        });
    }

    private void togglePasswordVisibility() {
        if (isPasswordVisible) {
            // 隐藏密码
            etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            ivPasswordToggle.setImageResource(R.drawable.ic_eye_closed);
            isPasswordVisible = false;
        } else {
            // 显示密码
            etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            ivPasswordToggle.setImageResource(R.drawable.ic_eye_open);
            isPasswordVisible = true;
        }
        
        // 将光标移动到文本末尾
        etPassword.setSelection(etPassword.getText().length());
    }

    private void checkLoginStatus() {
        // 如果用户已登录，直接跳转到主页面
        if (sessionManager.isLoggedIn()) {
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            finish();
        }
    }

    private void performLogin() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        // 输入验证
        if (!validateInput(username, password)) {
            return;
        }

        // 显示加载状态
        setLoadingState(true);

        // 在后台线程执行登录
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                final ApiResponse<User> response = apiService.login(username, password);
                
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        setLoadingState(false);
                        handleLoginResponse(response);
                    }
                });
            }
        });
    }

    private boolean validateInput(String username, String password) {
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(LoginActivity.this, "请输入用户名", Toast.LENGTH_SHORT).show();
            etUsername.requestFocus();
            return false;
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
            etPassword.requestFocus();
            return false;
        }

        return true;
    }

    private void handleLoginResponse(ApiResponse<User> response) {
        if (response == null) {
            Toast.makeText(LoginActivity.this, "网络连接失败，请检查网络设置", Toast.LENGTH_SHORT).show();
            return;
        }

        if (response.isSuccess()) {
            // 登录成功
            User user = response.getData();
            System.out.println("类型："+response.getMessage());
            if (user != null) {
                // 保存用户会话
                sessionManager.saveUserSession(user);
                
                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                
                // 跳转到主页面
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                finish();
            }
        } else {
            // 登录失败
            String errorMessage = response.getMessage();
            if (TextUtils.isEmpty(errorMessage)) {
                errorMessage = "用户名或密码错误";
            }
            Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
        }
    }

    private void setLoadingState(boolean isLoading) {
        progressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        btnLogin.setEnabled(!isLoading);
        btnLogin.setText(isLoading ? "登录中..." : "登录");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
        }
    }
}
